// Date.cpp
// Written by Jaeseok Kim (jseokkim@hotmail.com)
// 03/29/2010

#include <iostream>
#include <sstream>
#include <string>
#include "date.h"

using namespace std;

// Day of each month from Jan to Dec
const int Date::anDayOfMonth[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

Date::Date(const char *pszDate)
{
    // Initialize year, month, and day
    nYear = nMonth = nDay = 0;

    // Check the string length
    if (strlen(pszDate) != 10)
    {
        cout << "Date string length is not 10" << endl;
        return;
    }
    
    // Check separator
    if (pszDate[4] != '-' || pszDate[7] != '-')
    {
        cout << "Date string has wrong separator" << endl;
        return;
    } 
    
    // Convert string to integer
    // In case of error, 0 will be stored.
    istringstream issYear(string(pszDate, 4));
    issYear >> nYear;
    istringstream issMonth(string(pszDate + 5, 2));
    issMonth >> nMonth;
    istringstream issDay(string(pszDate + 8, 2));
    issDay >> nDay;
    
    if (!isValidDate())
    {
        cout << "Not valid date" << endl;
    }
}

void Date::prevDate()
{
    if (isValidDate())
    {
        if (--nDay == 0)
        {
            if (--nMonth == 0)
            {
                nMonth = 12;
                nYear --;
            }
    
            nDay = (isLeapYear() && nMonth == 2) ? 29 : anDayOfMonth[nMonth];
        }
    }
}

string Date::toString()
{
    string sDate;
    ostringstream osYear, osMonth, osDay;

    osYear.fill('0');
    osYear.width(4);
    osMonth.fill('0');
    osMonth.width(2);
    osDay.fill('0');
    osDay.width(2);

    if (isValidDate())
    {
        osYear << nYear;
        osMonth << nMonth;
        osDay << nDay;
        sDate = osYear.str() + "-" + osMonth.str() + "-" + osDay.str();
    }
    
    return sDate;
}
